package servlet.alipay;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import config.AlipayConfig;
import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;

/**
 * Servlet implementation class AliPayServlet
 */
@WebServlet(name="AliPayServlet",urlPatterns="/aliPayServlet")
public class AliPayServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private OrderService orderService = new OrderServiceImpl();
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		try {
				
			//获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
			
			//设置请求参数
			AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
			alipayRequest.setReturnUrl(AlipayConfig.return_url);
			alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
			
			String orderNO = request.getParameter("orderNO");
			Order order = orderService.findByOrderNO(orderNO);
			
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ order.getOrderNO() +"\"," 
					+ "\"total_amount\":\""+ order.getAmount() +"\"," 
					+ "\"subject\":\""+ order.getSubject() +"\"," 
					+ "\"body\":\""+ order.getBody() +"\"," 
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

			
			//请求
			String result = alipayClient.pageExecute(alipayRequest).getBody();
			//输出
			out.println(result);
			System.out.println(result);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
